package com.hzsai.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;

/**
 * hzsai 2019/8/29
 * usage:
 **/
public class JSONUtil {

    private static final Logger logger = LoggerFactory.getLogger(JSONUtil.class);

    public static String toJSONString(Object obj) {
        String ret = null;
        ObjectMapper mapper = new ObjectMapper();

        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd-HH:mm:ss");
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss"));
//        mapper.setDateFormat(dtf);

        logger.debug("JsonUtil-> obj: {}", obj.toString());
        try {
            ret = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
//            e.printStackTrace();
            logger.error(e.getMessage());
            logger.error("JSONUtil: 转换JSON失败");
        }

        return ret;
    }
}
